import { useState, useEffect } from 'react';

// 设备类型枚举
export const DEVICE_TYPE = {
  MOBILE: 'mobile',
  TABLET: 'tablet',
  DESKTOP: 'desktop'
};

// 断点配置
const BREAKPOINTS = {
  mobile: 768,
  tablet: 1200
};

/**
 * 检测设备类型的自定义Hook
 * @returns {Object} 包含设备类型和相关状态的对象
 */
export const useDevice = () => {
  const [deviceType, setDeviceType] = useState(DEVICE_TYPE.DESKTOP);
  const [windowWidth, setWindowWidth] = useState(
    typeof window !== 'undefined' ? window.innerWidth : 1200
  );

  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      setWindowWidth(width);
      
      if (width < BREAKPOINTS.mobile) {
        setDeviceType(DEVICE_TYPE.MOBILE);
      } else if (width < BREAKPOINTS.tablet) {
        setDeviceType(DEVICE_TYPE.TABLET);
      } else {
        setDeviceType(DEVICE_TYPE.DESKTOP);
      }
    };

    // 初始化设备类型
    handleResize();

    // 添加窗口大小变化监听器
    window.addEventListener('resize', handleResize);

    // 清理监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return {
    deviceType,
    windowWidth,
    isMobile: deviceType === DEVICE_TYPE.MOBILE,
    isTablet: deviceType === DEVICE_TYPE.TABLET,
    isDesktop: deviceType === DEVICE_TYPE.DESKTOP,
    isMobileOrTablet: deviceType === DEVICE_TYPE.MOBILE || deviceType === DEVICE_TYPE.TABLET
  };
};